package com.xingda.packing.http;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xingda.packing.common.DateUtils;
import com.xingda.packing.config.appset.AppSetUrl;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.util.UUID;

/**
 * 称重物
 *
 * @author LEGION
 */
@Slf4j
public class PackinvweighHttp {

    public static JSONObject getPostParam(JSONObject rJson) {

        JSONObject packinvplan = rJson.getJSONObject("packinvplan");
        JSONArray items = packinvplan.getJSONArray("items");

        JSONArray resultItemArray = new JSONArray();

        BigDecimal totalWeight = new BigDecimal("0.0");
        for (int i = 0; i < items.size(); i++) {
            JSONObject item = items.getJSONObject(i);
            JSONObject resultItemJson = new JSONObject();
            JSONObject packinvdoc = item.getJSONObject("packinvdoc");
            resultItemJson.put("pkPackinvdoc", packinvdoc.getString("pkPackinvdoc"));
            resultItemJson.put("pkPackinvtype", packinvdoc.getString("pkPackinvtype"));
            resultItemJson.put("nnum", item.getIntValue("nnum"));
            resultItemJson.put("nsweigh", packinvdoc.getBigDecimal("nweight"));
            BigDecimal nwight = packinvdoc.getBigDecimal("nweight").multiply(item.getBigDecimal("nnum"));
            resultItemJson.put("nweigh", nwight);
            resultItemArray.add(resultItemJson);
            totalWeight = totalWeight.add(nwight);
        }

        JSONObject resultJson = new JSONObject();
        resultJson.put("pkPacking", rJson.getString("pkPacking"));
        resultJson.put("pkCorp", rJson.getString("pkCorp"));
        resultJson.put("pkCalbody", rJson.getString("pkCalbody"));
        resultJson.put("weightime", DateUtils.getNowDate());
        resultJson.put("nweigh", totalWeight);
        resultJson.put("guid", UUID.randomUUID().toString());
        resultJson.put("items", resultItemArray);
        return resultJson;

    }

    public static JSONObject save(String pkPacking) {
        JSONObject packInfoJson = PackingRequireHttp.searchPackingBoxInspection(pkPacking, false, false, true, false);
        JSONObject postParamJson = getPostParam(packInfoJson);
        try {
            JSONObject entityJson = BaseHttp.postBody(AppSetUrl.pack_packinvweigh_url, postParamJson);
            log.info("包装物信息上传结果为：{}", entityJson.toJSONString());
            return entityJson;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
